
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart' ;
const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/html5/', 'm.ctrip.com/html5'];

class FWebView extends StatefulWidget {
  final String? title;
  String? url;
  final String? statusBarColor;
  final bool? hideAppBar;

  FWebView({this.title, this.statusBarColor, this.hideAppBar,this.url}){
      if (url != null && url!.contains('ctrip.com')) {
        //fix 携程H5 http://无法打开问题
        url = url!.replaceAll("http://", 'https://');
      }
  }

  @override
  State<FWebView> createState() => _FWebViewState();
}

class _FWebViewState extends State<FWebView> {

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor ?? 'ffffff';
    Color backButtonColor;
    if (statusBarColorStr == 'ffffff'){
      backButtonColor = Colors.black;
    }else {
      backButtonColor = Colors.white;
    }

    return Scaffold(
      body: Column(
        children: [
          _appBar(Color(int.parse('0xff' + statusBarColorStr)),backButtonColor),
          Expanded(
            child: WebView(
              initialUrl: widget.url,
              javascriptMode: JavascriptMode.unrestricted,
              navigationDelegate: (NavigationRequest navigation){
                if (_isToMai(navigation.url)){
                  Navigator.pop(context);
                  return NavigationDecision.prevent;
                }else {
                  return NavigationDecision.navigate;
                }
              },
            ),
          )

        ],
      ),
    );
  }

 bool _isToMai(String? url){
    bool contain = false;
    for (final value in CATCH_URLS){
      if(url?.endsWith(value) ?? false){
        contain = true;
        break;
      }
    }
    return contain;
  }

  _appBar(Color barColor,Color backButtonColor){
    if(widget.hideAppBar ?? false){
      return Container(
        color: barColor,
        height: 30,
      );
    }

    return Container(
      color: barColor,
      height: 88,
      padding: EdgeInsets.fromLTRB(0, 44, 0, 0),
      child: FractionallySizedBox(
        widthFactor: 1,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                margin: EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 26,
                ),
              ),
            ),


            Positioned(
              left: 40,
              right: 40,
              child: Container(
                child: Text(widget.title ?? "", style: TextStyle(fontSize: 20),textAlign: TextAlign.center,),
              ),
            )
          ],
        ),
      ),

    );
  }
}

